#include "itemreader.h"

itemReader::itemReader(QTreeWidget* treeWidget)
    : treeWidget(treeWidget)
{

}

bool itemReader::readFile(QIODevice* device)
{
    reader.setDevice(device);
    itemCount = 0;

    while (!reader.atEnd() && !reader.hasError())
    {
        reader.readNext();

        if (reader.isStartDocument())
            continue;

        if (reader.isStartElement())
        {
            if (reader.name() == "items")
            {
                continue;
            }
            else if (reader.name() == "weapon" || reader.name() == "shield" || reader.name() == "legs" || reader.name() == "head" || reader.name() == "hands" || reader.name() == "feet" || reader.name() == "body")
            {
                readItem(reader.name().toString());
                itemCount++;
            }
        }
    }

    /*while (reader.readNextStartElement())
    {
        readItem(reader.name());
    }*/

    return !reader.error();
}

void itemReader::readItem(QString type)
{
    QTreeWidgetItem* parent = treeWidget->findItems(type, Qt::MatchFixedString, 0)[0];
    QTreeWidgetItem* item = new QTreeWidgetItem();

    reader.readNext();

    while (!(reader.isEndElement() && reader.name().toString() == type))
    {
        if (reader.name() == "itemName") item->setText(0, reader.readElementText());
        if (reader.name() == "armor") item->setText(1, reader.readElementText());
        if (reader.name() == "damage") item->setText(2, reader.readElementText());
        if (reader.name() == "attackSpeed") item->setText(3, reader.readElementText());
        if (reader.name() == "itemLevel") item->setText(4, reader.readElementText());
        if (reader.name() == "requiredLevel") item->setText(5, reader.readElementText());
        if (reader.name() == "rarity") item->setText(6, reader.readElementText());
        if (reader.name() == "class") item->setText(7, reader.readElementText());
        if (reader.name() == "strBonus") item->setText(8, reader.readElementText());
        if (reader.name() == "dexBonus") item->setText(9, reader.readElementText());
        if (reader.name() == "staBonus") item->setText(10, reader.readElementText());
        if (reader.name() == "intBonus") item->setText(11, reader.readElementText());
        if (reader.name() == "wilBonus") item->setText(12, reader.readElementText());
        if (reader.name() == "maxCount") item->setText(13, reader.readElementText());
        if (reader.name() == "description") item->setText(14, reader.readElementText());
        if (reader.name() == "price") item->setText(15, reader.readElementText());

        reader.readNext();
    }

    parent->addChild(item);
}

QString itemReader::errorString() const
{
    return reader.errorString();
}

int itemReader::getItemCount()
{
    return itemCount;
}
